/**
 * innoTweets Addon
 * 
 * @author  Dino Babu (DBK)
 * @date    5 May 2014
 */

// Init Vars
var baseUrl = 'http://innotweets.innovaturelabs.org/';
//var baseUrl = 'http://192.168.1.124/innotweets/';
var lastNotifyCount = 0;
var notifySeen = true;

// Open New Tab
var tabs = require("sdk/tabs");
function openWebsite(url) {
  if (url) {
    tabs.open(url);
  } else {
    tabs.open(baseUrl);
  }
}

// Generate Toolbar Icon Image
function getIcon() {
  var logoFile = 'inno_twetts_logo.png';
  if (!notifySeen) {
    logoFile = 'inno_twetts_logo_notify.png';
  }
  return "<img style='height: 100%' src='" + baseUrl + "assets/img/" + logoFile + "'/>";
}

// Initiate Widget (Toolbar Icon)
var iconScript = "self.port.on('resetImage', function(imageTag) { document.body.innerHTML = imageTag; })";
var widgets = require('sdk/widget');
var widget = widgets.Widget({
  id: "innoTweets-link",
  label: "innoTweets",
  content: getIcon(),
  contentScript: iconScript,
  onClick: function() {
    notifySeen = true;
    openWebsite();
  }
});

// Show Notification
function notifyFF(title, text, url) {
  var notifications = require("sdk/notifications");
  notifications.notify({
    title: title,
    text: text,
    iconURL: baseUrl + 'assets/img/inno_twetts_logo.png',
    onClick: function() {
      notifySeen = true;
      openWebsite(url);
    }
  });
}

// Process Data
function process(data) {
  if (data.count > lastNotifyCount) {
    notifySeen = false;
    notifyFF(data.title, data.text, data.url);
  }
  lastNotifyCount = data.count;
}

// Send Request
function request() {
  var Request = require("sdk/request").Request;
  var getRequest = Request({
    url: baseUrl + 'notification/addon',
    onComplete: function(data) {
      process(data.json);
    }
  }).get();
}

// Reset Icon Image Every 1 Second
require("sdk/timers").setInterval(function() {
  widget.port.emit("resetImage", getIcon());
}, 1000);

// Requesting Every 30 Seconds
require("sdk/timers").setInterval(function() {
  request();
}, 30000);